package com.hyt.it.ogt.ks.login.oauth;


import com.hyt.it.ogt.ks.login.model.LoginTypeEnum;
import com.hyt.it.ogt.ks.login.remote.KsClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

/**
 * 
 * @ClassName: UserDetailsServiceImpl
 * @Description: 自定义UserDetailsService
 * @author liuq
 * @date 2021年1月15日
 *
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired
	HttpServletRequest request;

	@Autowired
	KsClient ksClient;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		username = username.toUpperCase();
		String examId = this.request.getParameter("password");
		String login_client = this.request.getParameter("login_client");
		String from = this.request.getParameter("from");
		String loginType = this.request.getParameter("login_type");
		String candidateId = this.ksClient.validCandidateAccount(username, examId, from,loginType).getData();
		log.error("从ks去验证当前登录考生信息返回为:【{}】,考生准考证为:【{}】",candidateId,username);
		if (StringUtils.isBlank(candidateId)) {
			throw new OAuth2Exception(getErrorMsg(loginType,examId,username));
		}
		Set<GrantedAuthority> grantedAuthorities = new HashSet();
		GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_KS");
		grantedAuthorities.add(authority);
		String password = new BCryptPasswordEncoder(5).encode(examId);
		User user = new User(candidateId + examId, password, true, true, true, true, grantedAuthorities);
		return user;
	}

	private String getErrorMsg(String loginType,String examId,String username){
		String msg = LoginTypeEnum.getMsg(NumberUtils.toInt(loginType, 0));
		return "登录信息错误！考试id：" + examId + "，" + msg + username;
	}
}
